const chokidar = require('chokidar');
const fs = require('fs').promises;
const path = require('path');
const {getFileType} = require("../util/file");
class FolderWatcher {
    constructor(fileServer) {
        this.fileServer = fileServer;
        this.watchers = new Map(); // 存储监控器实例
        this.fileCache = new Map(); // 存储文件状态缓存
    }

    // // 新增：启动文件监控
    // async startFileWatching() {
    //     console.log('👀 Starting file system monitoring...');
    //
    //     for (const vault of this.fileServer.config.vaults) {
    //         if (vault. !== false) { // 默认启用监控
    //             await this.watchVault(vault);
    //         }
    //     }
    // }

    // 新增：监控单个vault
    async watchVault(vault) {
        return new Promise((resolve, reject) => {
            try {
                console.log(`🔍 Setting up file watcher for: ${vault.path}`);

                const watcher = chokidar.watch(vault.path, {
                    ignored: /(^|[/\\])\../, // 忽略隐藏文件
                    persistent: true,
                    ignoreInitial: true,
                    depth: 10 // 监控深度
                });

                // 文件添加事件
                watcher.on('add', async (filePath) => {
                    await this.onFileAdded(vault, filePath);
                });

                // // 文件变化事件
                // watcher.on('change', async (filePath) => {
                //     await this.onFileChanged(vault, filePath);
                // });
                //
                // 文件删除事件
                watcher.on('unlink', async (filePath) => {
                    await this.onFileDeleted(vault, filePath);
                });

                // // 文件夹添加事件
                // watcher.on('addDir', async (dirPath) => {
                //     await this.onDirectoryAdded(vault, dirPath);
                // });
                //
                // // 文件夹删除事件
                // watcher.on('unlinkDir', async (dirPath) => {
                //     await this.onDirectoryDeleted(vault, dirPath);
                // });

                // 错误处理
                watcher.on('error', (error) => {
                    console.error(`❌ Watcher error for ${vault.name}:`, error);
                });

                // 准备就绪
                watcher.on('ready', () => {
                    console.log(`✅ File watcher ready for vault: ${vault.name}`);
                    this.watchers.set(vault.name, watcher);
                    resolve(watcher);
                });

                // 设置超时
                setTimeout(() => {
                    if (!this.watchers.has(vault.name)) {
                        reject(new Error(`Watcher setup timeout for vault: ${vault.name}`));
                    }
                }, 10000);

            } catch (error) {
                console.error(`❌ Failed to setup watcher for ${vault.name}:`, error);
                reject(error);
            }
        });
    }

    // 新增：处理文件添加
    async onFileAdded(vault, filePath) {
        // 检查文件是否符合vault的模式
        for (const pattern of vault.patterns) {
            if (!pattern.test(filePath)) {
                return;
            }
        }

        try {
            const stats = await fs.stat(filePath);
            const relativePath = path.relative(vault.path, filePath);

            console.log(`📄 New file detected in ${vault.name}: ${relativePath}`);

            const fileInfo = {
                path: filePath,
                name: path.basename(filePath),
                relativePath: relativePath,
                type: getFileType(path.basename(filePath)),
                isDirectory: false,
                size: stats.size,
                mtime: stats.mtime,
            };

            const routes = this.fileServer.routeMapper.mapFilesToRoutes([fileInfo], vault);

            for (const route of routes) {
                if (this.fileServer.routes.has(route.route)) {
                    console.log(`🔄 Updating existing route: ${route.route}`);
                    this.fileServer.routes.set(route.route, route);
                } else {
                    console.log(`✨ Adding new route: ${route.route}`);
                    console.log(`registering route /${route.prefix}${route.route}#~:~hint=${route.description}`)
                    this.fileServer.routes.set(route.route, route);
                    this.fileServer.registerRoute(route);
                }
            }

            // 更新缓存
            // this.updateFileCache(vault, filePath, stats);

        } catch (error) {
            console.error(`❌ Failed to process new file ${filePath}:`, error);
        }
    }

    async onFileDeleted(vault, filePath) {
        // 这里监不监控其实不重要，只是在缓存中删除，不会真正注销这个路由
        for (const pattern of vault.patterns) {
            if (!pattern.test(filePath)) {
                return;
            }
        }

        try {
            const relativePath = path.relative(vault.path, filePath);
            console.log(`🗑️ File deleted in ${vault.name}: ${relativePath}`);

            // 找到并删除对应的路由
            const routesToRemove = [];
            for (const [route, info] of this.fileServer.routes.entries()) {
                if (info.filePath === filePath && info.vault === vault.name) {
                    routesToRemove.push(route);
                }
            }

            for (const route of routesToRemove) {
                this.fileServer.routes.delete(route);
                console.log(`🗑️ Removed route: ${route}`);
            }

            // 从缓存中删除
            // this.removeFromFileCache(vault, filePath);

        } catch (error) {
            console.error(`❌ Failed to process deleted file ${filePath}:`, error);
        }
    }
}

module.exports = FolderWatcher;